import Opinion from "../../../../model/opinion"
import FileUploader from "../../../../utils/file-uploader";
import { getDataSet, getEventParam } from "../../../../utils/util";
Component({
  properties: {
    taskId: String,
    status: String, // 角色
    formData: {
      type: Object,
      value: {}
    }
  },
  data: {
    ZhzxFiles: [], // 附件列表
    rules: [
      {name: 'expertOpinion',
       rules: [
         {required: true, message: '意见不能为空'},
         {minlength: 3, message: '内容不能少于3个字'}
       ]}
    ],
    error: '' // 报错信息
  },
  lifetimes: {
    async ready() {
      // await this._getMessageAPI();
      // this._getFilesAPI()
    }
  },
  methods: {
    // 获取附件列表
    async _getFilesAPI() {
      let query = {
        opinionId: this.data.formData.id,
        opinionType: this.data.status // 0 经理 1 专家 3 项目单位 4协作人
      }
      let {ZhzxFiles} = await Opinion.getMessageFiles(query);
      this.setData({
        ZhzxFiles
      })
    },
    // 上传附件
    async uploadFile(e) {
      const res = await wx.chooseMessageFile({
        count: 1,
        type: 'file'
      })
      let filePath = res.tempFiles[0].path
      let query = {
        opinionId: this.data.formData.id,
        fileRealName: res.tempFiles[0].name, // 文件名
        bucketName: 'yijian', // bucket名称
        opinionType: this.data.status, // 0 经理 1 专家 3 项目单位 4协作人
      }
      await FileUploader.uploadExpertFile(filePath, query)
      this._getFilesAPI()
    },
    // 删除附件
    async handleRemove(e) {
      let fileId = Number(getDataSet(e, 'id')) 
      let res = await Opinion.deleteFileOpinion({fileId: fileId})
      wx.showToast({
        title: res.msg,
        icon: 'none',
        duration: 3000,
      })
      this._getFilesAPI()
    },
    handleInputChange(event) {
      const value = getEventParam(event, 'value')
      this.setData({
          ['formData.expertOpinion']: value
      })
  },
    handleSubmit() {
      this.selectComponent('#form').validate(async (valid, errors) => {
        if(!valid) {
          const errMsg = errors.map(error => error.message)
                this.setData({
                    error: errMsg.join(';')
                })
                return
        }
        wx.showLoading({
          title: '正在提交',
          mask: true
        })
        // 调上传api
        let res = await Opinion.updateExpertOpinion({...this.data.formData, opinionType: this.data.status})
        
        wx.hideLoading()
        if(res.code == 200) {
          wx.showToast({
            title: '提交成功',
            icon: 'none',
            duration: 3000,
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 3000,
          })
        }
      })
    },
  }
})